<template>
    <div class="fund-dialog">
        <el-dialog
            title="模型参数设置"
            :visible.sync="dialogVisible"
            width="40%"
            top="5vh"
            :before-close="handleClose"
            :close-on-click-modal='false'
        >
            <div class="content">
                <div class="content-left">
                    <HeaderTitle>
                        <div slot="title">产品清单</div>
                    </HeaderTitle>
                    <el-tabs v-model="activeName" stretch>
                        <el-tab-pane label="产品组" name="first">
                            <el-input placeholder="搜索产品" v-model="filterFundGroup" size="mini" style="margin-top:5px"> </el-input>
                            <div class="tree-node">
                                <el-tree
                                    v-loading="fundGroupLoading"
                                    :key="fundGroupKey"
                                    node-key="id"
                                    ref="treeFundGroup"
                                    class="filter-tree"
                                    :data="fundGroupData"
                                    show-checkbox
                                    :props="defaultProps"
                                    :filter-node-method="filterNode"
                                    @check="handleCheckChangeFundGroup"
                                >
                                </el-tree>    
                            </div>
                        </el-tab-pane>
                        <el-tab-pane label="产品" name="second">
                            <el-input placeholder="搜索产品" v-model="filterFund" size="mini" style="margin-top:5px"> </el-input>
                            <div class="tree-node">
                                <el-tree
                                    :key="fundKey"
                                    node-key="id"
                                    ref="treeFund"
                                    class="filter-tree"
                                    :data="fundData"
                                    show-checkbox
                                    default-expand-all
                                    :props="defaultProps"
                                    :filter-node-method="filterNode"
                                    @check="handleCheckChangeFund"
                                >
                                </el-tree>    
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>
                <div class="content-right">
                    <HeaderTitle>
                        <div slot="title">已选产品（组）</div>
                    </HeaderTitle>
                    <div class="right-btn">
                        <el-button type="danger" @click="deleteFund">删除</el-button>
                        <el-button type="primary" @click="checkAllFund">全选</el-button>
                    </div>
                    <div class="right-node">
                        <el-tree
                            :key="checkTree"
                            node-key="id"
                            ref="treeCheckFund"
                            class="filter-tree"
                            :data="checkFundData"
                            show-checkbox
                            default-expand-all
                            :props="defaultProps"
                            @check="handleCheckFund"
                        >
                        </el-tree>    
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="checkDataList('cancel')">取 消</el-button>
                <el-button type="primary" @click="checkDataList('confirm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch, Emit } from 'vue-property-decorator';
import { SGU_CACHE } from '@/utils/diction-const-util';
import HeaderTitle from './header-title.vue';

@Component({
    name: 'FundDialog',
    components: {
        HeaderTitle
    },
})
export default class FundDialog extends Vue {
    @Prop() fundVisible; // dialog开关
    dialogVisible:boolean = false; // dialog开关
    activeName: string = 'first'; // tab页切换
    filterFundGroup = ''; // 产品组输入文本
    filterFund = ''; // 产品输入文本
    checkFundData = []; // 已选产品（组）数据列表
    checkFundDataKeys = []; // 已选产品（组）数据列表-选中
    defaultProps = {
      children: 'children',
      label: 'label',
    };
    fundGroupData = []; // 产品组tree数据
    fundData = []; // 产品tree数据
    fundGroupKey:number = -1; // 产品组treekey
    fundKey:number = -1; // 产品treekey
    CheckChangeFundGroup = [];
    CurrentFundGroupKeys = []; // 产品组当前选中所有产品id值
    CurrentFundGroupList = []; // 产品组当前选中所有产品对象数据
    CheckChangeFund = []; // 产品维度当前选中的所有产品
    CurrentFundKeys = []; // 产品当前选中所有产品id值 + 产品组
    checkTree: number = 0;
    fundGroupLoading: boolean = false;
    // 监听打开dialog
    @Watch('fundVisible')
    async watchFundVisible(newVal, oldVal) {
        this.dialogVisible = newVal;
        if (this.fundGroupData.length) {
            return
        }
        if (this.dialogVisible) {
            this.getGroupWithFundInfo();
            let fubds = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
            this.fundData = [];
            for (let itme of fubds) {
                let datas = itme.fundCode + '-' + itme.fundName;
                this.fundData.push({ label: datas, id: itme.fundCode, fundCode: itme.fundCode });
            }
        }
    }
    // 监听打开dialog
    @Watch('dialogVisible')
    watchDialogVisible(newVal, oldVal) {
        if (newVal == false) {
            this.$emit('emitCheckGroup', this.checkFundData, 'cancel');
        }
    }
    // 产品组搜索
    @Watch('filterFundGroup')
    watchFilterFundGroup(val) {
        (this.$refs.treeFundGroup as any).filter(val);
    }
    // 产品搜索
    @Watch('filterFund')
    watchFilterFund(val) {
        (this.$refs.treeFund as any).filter(val);
    }
    @Watch('CheckChangeFundGroup', {deep: true})
    watchCheckChangeFundGroup(newVal, oldVal) {
    // el-tree 由于同在产品会出现在不同产品组里，此方法为了实现点击a产品组的A产品，回显成功勾选在其他产品组中的A产品
        let checkedKeys = [];
        newVal[0].checkedNodes.forEach(item => {
            if (item.level == '2') {
                checkedKeys.push(item.id)
            }
        })
        if (oldVal.length == 0) {
            // 第一次点击选择checkout
            newVal[0].checkedNodes.forEach(item => {
                if (item.level == '2') {
                    this.fundGroupData.forEach(item2 => {
                        item2.children.forEach(item3 => {
                            if (item3.fundCode == item.fundCode) {
                                this.CurrentFundGroupKeys.push(item3.id);
                                this.CurrentFundGroupList.push(item3);
                            }
                        })
                    })
                }
            })
            this.$nextTick(() => {
                (this.$refs.treeFundGroup as any).setCheckedKeys(this.CurrentFundGroupKeys);
            })
        } else if (this.CurrentFundGroupKeys.length < checkedKeys.length) {
            // 点击选中
            // 找出选中的产品对象数据和fundCode
            let resultKeys = [];
            let resultFundCode = []
            newVal[0].checkedNodes.forEach((item1, index1) => {
                let checkBool = false
                this.CurrentFundGroupList.forEach((item2, index2) => {
                   if (item1.id === item2.id) {
                     checkBool = true
                   }
                 })
                if (!checkBool) {
                    resultFundCode.push(item1.fundCode)
                }
            })
            // 遍历所有产品中ID一致的给选中
            this.fundGroupData.forEach(item1 => {
                item1.children.forEach(item2 => {
                    if (resultFundCode.includes(item2.fundCode)) {
                        this.CurrentFundGroupKeys.push(item2.id);
                        this.CurrentFundGroupList.push(item2);
                    }
                })
            })
            this.$nextTick(() => {
                (this.$refs.treeFundGroup as any).setCheckedKeys(this.CurrentFundGroupKeys);
            })
        } else if (this.CurrentFundGroupKeys.length > checkedKeys.length) {
            // 找出取消选中的产品对象数据和fundCode
            let resultKeys = [];
            let resultFundCode = []
            this.CurrentFundGroupList.forEach((item1, index1) => {
                let checkBool = false
                newVal[0].checkedNodes.forEach((item2, index2) => {
                   if (item1.id === item2.id) {
                     checkBool = true
                   }
                 })
                if (!checkBool) {
                    resultFundCode.push(item1.fundCode)
                }
            })
            // 找到点击取消的fundCode,遍历删除都是这个fundCode的数据
            for (let i = this.CurrentFundGroupList.length - 1; i >= 0; i--) {
                if (resultFundCode.includes(this.CurrentFundGroupList[i].fundCode)) {
                    resultKeys.push(this.CurrentFundGroupList[i].id);
                    this.CurrentFundGroupList.splice(i, 1);
                }
            }
            // 找到点击取消的fundCode,遍历删除都是这个fundCode的数据id
            for (let i = this.CurrentFundGroupKeys.length - 1; i >= 0; i--) {
                if (resultKeys.includes(this.CurrentFundGroupKeys[i])) {
                    this.CurrentFundGroupKeys.splice(i, 1);
                }
            }
            this.$nextTick(() => {
                (this.$refs.treeFundGroup as any).setCheckedKeys(this.CurrentFundGroupKeys);
            })
        }
        let checkFundData = [];
        if (this.CurrentFundGroupList.length != 0) {
            this.CurrentFundGroupList.forEach(item => {
                checkFundData.push({
                    id: item.fundCode,
                    label: item.label,
                    fundCode: item.fundCode,
                })
            })    
        }
        this.CheckChangeFund.forEach(item => {
            checkFundData.push({
                id: item.id,
                label: item.label,
                fundCode: item.fundCode
            })
        })
        this.checkFundData = this.setObject(checkFundData);
    }
    async mounted() {
        // console.log('++++++')
        // this.getGroupWithFundInfo();
    }
    private getGroupWithFundInfo() {
        this.fundGroupLoading = true;
        this.$axios.get('/fundGroup/getGroupWithFundInfo')
        .then((res: any) => {
            this.$nextTick(() => {
                // console.log('选择组合数据', res)
                this.fundGroupData = [];
                this.fundGroupData = res;
                this.fundGroupLoading = false;
            })
        })
    }
    // 过滤
    filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    }
    // 产品组选中
    handleCheckChangeFundGroup(data, checked, indeterminate) {
        this.CheckChangeFundGroup = [];
        this.CheckChangeFundGroup.push(checked)
    }
    // 产品选中
    handleCheckChangeFund(data, checked, indeterminate) {
        let nodes = [];
        checked.checkedNodes.forEach(item => {
            nodes.push({
                id: item.id,
                label: item.label
            })    
        });
        this.CheckChangeFund = checked.checkedNodes;
        let checkFundData = [];
        this.CheckChangeFund.forEach(item => {
            checkFundData.push({
                id: item.id,
                label: item.label,
                fundCode: item.fundCode
            })
        })
        this.CurrentFundGroupList.forEach(item => {
            checkFundData.push({
                id: item.id,
                label: item.label,
                fundCode: item.fundCode
            })
        })
        this.checkFundData = this.setObject(checkFundData);
    }
    // 已选产品选中
    handleCheckFund(data, checked, indeterminate) {
        this.checkFundDataKeys = [];
        checked.checkedNodes.forEach(item => {
            this.checkFundDataKeys.push(item.fundCode)    
        });
    }
    // 删除已选产品
    deleteFund() {
        if (this.checkFundDataKeys.length == 0) {
            this.$message.warning('请选择产品！')
            return
        }
        this.$nextTick(() => {
            for (let i = this.checkFundData.length - 1; i >= 0; i--) {
                if (this.checkFundDataKeys.includes(String(this.checkFundData[i].id))) {
                    this.checkFundData.splice(i, 1);
                }
            }  
            this.checkTree++;  
            // 取消选择产品组产品
            let delList = [];
            for (let i = this.CurrentFundGroupList.length - 1; i >= 0; i--) {
                if (this.checkFundDataKeys.includes(this.CurrentFundGroupList[i].id) || this.checkFundDataKeys.includes(this.CurrentFundGroupList[i].fundCode)) {
                    delList.push(this.CurrentFundGroupList[i].id);
                    this.CurrentFundGroupList.splice(i, 1);
                }
            }
            for (let i = this.CurrentFundGroupKeys.length - 1; i >= 0; i--) {
                if (delList.includes(this.CurrentFundGroupKeys[i])) {
                    this.CurrentFundGroupKeys.splice(i, 1);
                }
            }
            (this.$refs.treeFundGroup as any).setCheckedKeys(this.CurrentFundGroupKeys);
            // 取消选择产品维度的产品
            let retainList = [];
            this.CheckChangeFund.forEach(item => {
                if (!this.checkFundDataKeys.includes(item.fundCode)) {
                    retainList.push(item.fundCode);
                }
            });
            (this.$refs.treeFund as any).setCheckedKeys(retainList);
            this.checkFundDataKeys = [];
        })
    }
    // 全选
    checkAllFund() {
        this.$nextTick(() => {
            (this.$refs.treeCheckFund as any).setCheckedNodes(this.checkFundData)
            this.checkFundData.forEach(item => {
                this.checkFundDataKeys.push(item.fundCode)    
            });
        })
    }
    // 选择组合
    checkDataList(param1) {
        this.dialogVisible = false;
        if (param1 == 'confirm') {
            this.$emit('emitCheckGroup', this.checkFundData, param1);
        } else if (param1 == 'cancel') {
            this.$emit('emitCheckGroup', this.checkFundData, param1);
        }
    }
    // 数组对象自身根据某个字段去重
    setObject(persons) {
        let data = [];
        persons.forEach(item => {
          if (data.length == 0) {
            data.push(item);
          } else {
            let isDiff = true; // 是否不同
            for (let i = 0; i < data.length; i++) {
              let dataItem = data[i];
              if (dataItem.fundCode == item.fundCode) {
                // /*集合中已经存在相同数据*/
                isDiff = false;
                break;
              }
            }

            if (isDiff) {
              data.push(item);
            }
          }
        });
        return data
    }
}
</script>
<style lang="scss" scoped>
.content {
    width: 100%;
    display: flex;
    .content-left {
        width: 50%;
        height: 55vh;
        border-right: 1px solid #dfdfdf;
    }
    .content-right {
        width: 50%;
        // height: 300px;
        .right-btn {
            width: 95%;
            height: 34px;
            margin-top: 5px;
            padding-left: 10px;
            border-bottom: 1px solid #dfdfdf;
        }
        .right-node {
            height: 45vh;
            padding-top: 15px;
            overflow: auto;
        }
    }
}
.tree-node {
    height: 40vh;
    overflow: auto;
}
/deep/ .el-dialog .el-dialog__body {
    padding: 0px;
    height: 70vh;
}
</style>
